package com.newflypig.jblog.util;

import java.util.List;

import javax.servlet.http.HttpSession;

import org.springframework.util.StringUtils;

import com.newflypig.jblog.exception.LoginException;
import com.newflypig.jblog.model.BlogConfig;

/**
 *	blog工具类 
 *	@author newflypig
 *	time：2015年12月4日
 *
 */
public class BlogUtils {
	/**
	 * 判断是否已经登录
	 * @param session
	 * @throws RuntimeException
	 */
	public static void checkPermission(HttpSession session) throws RuntimeException{
		if(session.getAttribute(BlogConfig.SYSTEM)==null)
			throw new LoginException("You do not have Permission to perform this Operation,Please Login first.");
	}
	
	/**
	 * 将原始HTML转义成浏览器能识别的字符串
	 * @param content
	 * @return
	 */
	public static String html(String content) {
		if (content == null)
			return "";
		
		content=content
			.replaceAll("'",  "&apos;")
			.replaceAll("\"", "&quot;") // "
			.replaceAll("\t", "&nbsp;&nbsp;")// 替换跳格
			.replaceAll(" ",  "&nbsp;")// 替换空格
			.replaceAll("<",  "&lt;")
			.replaceAll(">",  "&gt;");

		return content;
	}
	
	public static String textarea(String content){
		if(content == null)
			return "";
		
		content = content
				.replaceAll("<textarea>", "&lt;textarea&gt;")
				.replaceAll("</textarea>", "&lt;/textarea&gt;");
		
		return content;
	}
	
	/**
	 * 将转义后的HTML恢复成原始HTML
	 * @param content
	 * @return
	 */
	public static String deHtml(String content){
		if (content == null)
			return "";
		
		content=content
				.replaceAll("&apos;",  "'")
				.replaceAll("&quot;", "\"") // "
				.replaceAll("&nbsp;&nbsp;", "\t")// 替换跳格
				.replaceAll("&nbsp;",  " ")// 替换空格
				.replaceAll("&lt;",  "<")
				.replaceAll("&gt;",  ">");

		return content;
	}
	
	/**
	 * 判断一组tags中是否有标题为tag的
	 * @param tags
	 * @param tag
	 * @return
	 */
	public static boolean tagListContainsStr(List<String> tagsTitle, String tagTitle) {
		return tagsTitle.stream().anyMatch(title -> {
			return title.equalsIgnoreCase(tagTitle);
		});
	}

	public static boolean isEmpty(String... args) {
		for(String str : args){
			if(StringUtils.isEmpty(str))
				return true;
		}
		return false;
	}
}
